<template>
    <form>
        <table>
            <tr>
                <td> 书名 <input type="text" v-model="formData.bookName"></td>
            </tr>
            <tr>
                <td>作者<input type="text" v-model="formData.author"></td>
            </tr>
            <tr>
                <td><input type="button" value="保存" @click="btnSave"></td>
                <td><input type="button" value="取消" @click="btnCancel"></td>
            </tr>
        </table>
    </form>
</template>

<script setup>

import{useRouter,useRoute} from'vue-router'
import { addItem, editItem, getById } from '@/api/bookApi';
import {onMounted ,reactive} from 'vue';

let router=useRouter()
let route=useRoute()

let formData=reactive({
    bookName:'',
    author:''
})

async function btnSave() {
    let id=route.params.id || 0;
    let res;
    if (id) {
        res =await editItem(id,formData);

    } else {
        res =await addItem(formData)
    }
    if (res.code === 1000) {
         router.push('/book')
    } else {
        console.log(res.msg);
        
    }
}

function btnCancel() {
    router.push('/book')
}

onMounted(async () => {
    let id =route.params.id || 0;

    let res =await getById(id);
    
    Object.assign(formData, res.data)
})

</script>